package com.example.andenginegame;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.util.FPSLogger;
import org.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePack;
import org.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePackLoader;
import org.andengine.extension.texturepacker.opengl.texture.util.texturepacker.TexturePackTextureRegionLibrary;
import org.andengine.extension.texturepacker.opengl.texture.util.texturepacker.exception.TexturePackParseException;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.debug.Debug;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.andengineConstant.GameConstant;
import com.example.andengineScene.MainScene;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.DisplayMetrics;
import android.view.KeyEvent;


public class MainActivity extends SimpleBaseGameActivity {
	private final static  String configFileName = "config.json";
	@SuppressLint("SimpleDateFormat")
	public SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	public  int CAMERA_WIDTH ;
	public  int CAMERA_HEIGH ;
	public int score = 0;
	public int maxScore= 0;
	public TexturePackTextureRegionLibrary ur1;
	public TexturePackTextureRegionLibrary ur2;
	public TexturePackTextureRegionLibrary ur3;
	private Camera camera ;
	public float xscale;
	public float yscale;
	private  ArrayList<Style> styles  = new ArrayList<Style>() ;
	private  ArrayList<Mission> missions = new ArrayList<Mission>();
	private  ArrayList<MissionOfType> missionTypes = new ArrayList<MissionOfType>();
	
	
	public ArrayList<Style> getStyles() {
		return styles;
	}

	public ArrayList<Mission> getMissions() {
		return missions;
	}

	public ArrayList<MissionOfType> getMissionTypes() {
		return missionTypes;
	}


	public MainScene mainScene;

	private int missionId;
    private int choseId  ;
	public int missionFinishNum;//锟斤拷锟斤拷锟斤拷戏锟斤拷傻锟斤拷锟斤拷锟�
	
    public Engine mEng;
    private  BitmapTextureAtlas mBitmapTextureAtlas;
    public TextureRegion mParticleTextureRegion;
	public Sound clickSound;
	public Sound deathSound;
	public Sound recordSound;
	public Sound launchSound;
	public Sound boomSound;
	public Sound boom_perfectSound;
	
	public MyScore myScore;
	
	/*  totalScore -- 锟杰得凤拷
	   *  totalPlayGameNum -- 锟斤拷锟斤拷戏锟斤拷锟斤拷
	   *  totalPrefectNUm -- 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
	   *  today_date -- 锟斤拷锟斤拷锟斤拷锟斤拷
	   *  todayScore -- 锟斤拷锟秸得凤拷
	   *  todayPrefectNum -- 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
	   *  todayPlayGameNum -- 锟斤拷锟斤拷锟斤拷戏锟斤拷锟斤拷
	   *  todayMaxScore 
	   *  totalMaxScore
	   */
	public String today_date;
	public int totalScore;
	public int totalPlayGameNum;
	public int totalPrefectNum;
	public int todayScore;
	public int todayPrefectNum;
	public int todayPlayGameNum;
	public int todayMaxScore;
	public int totalMaxScore;
	@Override
	public EngineOptions onCreateEngineOptions() {
		DisplayMetrics  dm = new DisplayMetrics();     
		   
		getWindowManager().getDefaultDisplay().getMetrics(dm);     
		   
		CAMERA_WIDTH = dm.widthPixels;               
		   
		CAMERA_HEIGH = dm.heightPixels;
		
		xscale = CAMERA_WIDTH/480;
		yscale = CAMERA_HEIGH/960;
		
	    this.camera = new Camera(0,0,CAMERA_WIDTH,CAMERA_HEIGH);
	 
	     EngineOptions engineop = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH,CAMERA_HEIGH), this.camera);
	     engineop.getAudioOptions().setNeedsSound(true);
	     return engineop;
	}

	@Override
	protected void onCreateResources() {
		
		
		//锟斤拷取锟斤拷锟斤拷锟斤拷锟�
		 readDataOfGame();
		
        //锟斤拷锟斤拷锟斤拷锟斤拷锟侥硷拷
		 parserConfigfile();
        
		
		
		try {
			final TexturePack spritesheetTexturePack = new TexturePackLoader(this.getTextureManager(), "gfx/").loadFromAsset(this.getAssets(), "ui1.xml");
			spritesheetTexturePack.loadTexture();
			this.ur1 = spritesheetTexturePack.getTexturePackTextureRegionLibrary();
			final TexturePack spritesheetTexturePack1 = new TexturePackLoader(this.getTextureManager(), "gfx/").loadFromAsset(this.getAssets(), "ui2.xml");
			spritesheetTexturePack1.loadTexture();
			this.ur2 = spritesheetTexturePack1.getTexturePackTextureRegionLibrary();
			final TexturePack spritesheetTexturePack2 = new TexturePackLoader(this.getTextureManager(), "gfx/").loadFromAsset(this.getAssets(), "ui0.xml");
			spritesheetTexturePack2.loadTexture();
			this.ur3 = spritesheetTexturePack2.getTexturePackTextureRegionLibrary();
			 mBitmapTextureAtlas = new BitmapTextureAtlas(getTextureManager(), 32, 32, TextureOptions.BILINEAR);  
		     mParticleTextureRegion = this.ur3.get(24);
		     mBitmapTextureAtlas.load();  	
		} catch (final TexturePackParseException e) {
			Debug.e(e);
		}
		SoundFactory.setAssetBasePath("sound/");
		try {
			this.clickSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "click.mp3");
			this.boomSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "boom.mp3");
			this.boom_perfectSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "boom_perfect.mp3");
			this.launchSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "launch.mp3");
			this.deathSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "death.mp3");
			this.recordSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "record.mp3");
	
		} catch (final IOException e) {
			Debug.e(e);
		}
		
		
	}
	/**
	 * 锟斤拷锟斤拷锟斤拷锟斤拷锟侥硷拷
	 */
   private void parserConfigfile() {
	   
	   
	    
	     String jsonStr = AppJsonFileReader.getJson(getBaseContext(),    
				configFileName);  	
	     JSONTokener jsonParser = new JSONTokener(jsonStr);  
		
		 JSONObject person;
			try {
			person = (JSONObject) jsonParser.nextValue();
				  // 锟斤拷锟斤拷锟斤拷锟侥撅拷锟斤拷JSON锟斤拷锟斤拷牟锟斤拷锟斤拷锟� 
			  JSONArray missionarray = person.getJSONArray("mission");  
			  
			  // 锟斤拷锟斤拷锟斤拷锟斤拷
			   parseMission(missionarray);
			
			  JSONArray missionTypearray = person.getJSONArray("missionType");  
			  // 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
			  parseMissionStype(missionTypearray);
			  
			  JSONArray stylearray = person.getJSONArray("style");
			  
			  //锟斤拷锟斤拷锟斤拷色锟斤拷锟斤拷
			  parseStyle(stylearray);
			 
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}  
		
	}
   /**
    * 锟斤拷锟斤拷锟斤拷色
    * @param stylearray
    */
private void parseStyle(JSONArray stylearray) {
	 for (int i = 0; i < stylearray.length(); i++) {
			
	    	try {
				
				JSONObject jso = (JSONObject) stylearray.get(i);
		        int ids = jso.getInt("id");
		        Style style = new Style();
		        style.setId(ids);
		        String name = jso.getString("name");
		        style.setName(name);
		        int needMissionNum = jso.getInt("needMissionNum");
		        style.setNeedMissionNum(needMissionNum);
		        int score = jso.getInt("score");
		        style.setScore(score);
		        String color_me = jso.getString("color_me");
		        style.setColor_me(color_me);
		        String color_bg = jso.getString("color_bg");
		        style.setColor_bg(color_bg);
		        String color_target = jso.getString("color_target");
		        style.setColor_target(color_target);
		        styles.add(style);
		      
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
/**
 * 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
 * @param missionTypearray
 */
private void parseMissionStype(JSONArray missionTypearray) {
	  for (int i = 0; i < missionTypearray.length(); i++) {
			
	    	try {
				
				JSONObject jso = (JSONObject) missionTypearray.get(i);
		        String type = jso.getString("type");
		        MissionOfType missionStyle = new MissionOfType();
		        missionStyle.setType(type);
		        String desc = jso.getString("desc");
		        missionStyle.setDesc(desc);
		    
				missionTypes.add(missionStyle);
		      
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

/**
 * 锟斤拷锟斤拷锟斤拷锟�
 * @param missionarray 
 */
   
private void parseMission(JSONArray missionarray) {
		
	  for (int i = 0; i < missionarray.length(); i++) {
			
	    	try {
				
				JSONObject jso = (JSONObject) missionarray.get(i);
		        int ids = jso.getInt("id");
		        Mission missionStyle = new Mission();
		        missionStyle.setId(ids);
		        String type = jso.getString("type");
		        missionStyle.setType(type);
		        
		        int needNum = jso.getInt("needNum");
		        missionStyle.setNeedNum(needNum);
		       
		        missions.add(missionStyle);
		      
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

  /**
   * 锟斤拷取锟斤拷锟斤拷锟斤拷锟�
   *  missionId -- 锟斤拷锟斤拷锟斤拷锟侥碉拷锟斤拷锟斤拷id
   *  score --- 每锟街得凤拷
   *  maxScore --锟斤拷训梅锟�
   *  choseId -- 锟斤拷选图锟斤拷Id
   *  missionFinishNum -- 锟斤拷锟斤拷锟斤拷锟斤拷锟�
   *  totalScore -- 锟杰得凤拷
   *  totalPlayGameNum -- 锟斤拷锟斤拷戏锟斤拷锟斤拷
   *  totalPrefectNUm -- 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
   *  today_date -- 锟斤拷锟斤拷锟斤拷锟斤拷
   *  todayScore -- 锟斤拷锟秸得凤拷
   *  todayPrefectNum -- 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
   *  todayPlayGameNum -- 锟斤拷锟斤拷锟斤拷戏锟斤拷锟斤拷
   */
	private void readDataOfGame() {
		 
		 SharedPreferences sharedPreferences = getSharedPreferences("SP", 
				 Activity.MODE_PRIVATE); 
		 missionId = sharedPreferences.getInt(GameConstant.MISSION_ID, GameConstant.ONE); 
		 score = sharedPreferences.getInt(GameConstant.SCORE, GameConstant.ZERO); 
		 maxScore = sharedPreferences.getInt(GameConstant.MAXSCORE,GameConstant.ZERO); 
		 choseId = sharedPreferences.getInt(GameConstant.CHOSETYPEID, GameConstant.ZERO); 
		 missionFinishNum = sharedPreferences.getInt(GameConstant.MISSIONFINISHNUM, GameConstant.ZERO); 
		 today_date = sharedPreferences.getString(GameConstant.TODAT_DATE, "null");
		 totalScore = sharedPreferences.getInt(GameConstant.TOTAL_SCORE,GameConstant.ZERO);
		 totalPlayGameNum = sharedPreferences.getInt(GameConstant.TOTAL_PLAYGAMENUM, GameConstant.ZERO);
		 totalPrefectNum  = sharedPreferences.getInt(GameConstant.TOTAL_PREFECTNUM, GameConstant.ZERO);
		 totalMaxScore = sharedPreferences.getInt(GameConstant.TOTAL_MAXSCORE, GameConstant.ZERO);
		 
		 if(today_date.equals(sf.format(new Date()))){
		  
			 todayPlayGameNum = sharedPreferences.getInt(GameConstant.TODAY_PLAYGAMENUM, GameConstant.ZERO);
			 todayPrefectNum = sharedPreferences.getInt(GameConstant.TODAY_PREFECTNUM, GameConstant.ZERO);
			 todayScore = sharedPreferences.getInt(GameConstant.TODAY_SCORE, GameConstant.ZERO);
			 todayMaxScore = sharedPreferences.getInt(GameConstant.TODAY_MAXSCORE, GameConstant.ZERO);
				
			 
		 }else{
			 todayPlayGameNum = 0;
			 todayPrefectNum = 0;
			 todayScore = 0;
			 todayMaxScore =0;
				
		 }
		
	}

	@Override
	protected Scene onCreateScene() {
		
		
		mEng = this.mEngine;
		this.mEng.registerUpdateHandler(new FPSLogger());
		
	    mainScene = new MainScene(this,choseId,this.getStyles(),this.getMissions(),missionId,this.getMissionTypes());
	
	
		return mainScene;
	}

	@Override
	public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
		if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
			return super.onKeyDown(pKeyCode, pEvent);
		} else {
		
			if(this.mEngine.isRunning()) {
					
			
			} else {
				
			
				SharedPreferences mySharedPreferences= this.getSharedPreferences("SP", 
				Activity.MODE_PRIVATE); 
				//实锟斤拷SharedPreferences.Editor锟斤拷锟襟（第讹拷锟斤拷锟斤拷 
				SharedPreferences.Editor editor = mySharedPreferences.edit(); 
				//锟斤拷putString锟侥凤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�
			    editor.putInt(GameConstant.SCORE, this.mainScene.score); 
				if (maxScore<this.mainScene.score){
				editor.putInt(GameConstant.MAXSCORE, this.mainScene.score); 
				
				}
				editor.commit(); 
			
			}	
			return true;	
		}
	}





}
